package com.hsc.account;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import javax.mail.Flags;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Part;
import javax.mail.internet.MimeMessage;

import com.hsc.db.tools.AccountList;
import com.hsc.db.tools.AccountService;
import com.hsc.db.tools.DBOpenHelper;
import com.hsc.db.tools.EmailService;
import com.hsc.db.tools.ItemList;
import com.hsc.db.tools.ItemService;
import com.hsc.db.tools.ReciveOneMail;
import com.hsc.db.tools.StringUtils;


import android.R.integer;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.text.format.Time;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class oneActivity extends Activity {
	private GridView dateview;
	private SimpleAdapter sim_adapter;
	public static List<Map<String, Object>> data_list=null;

	private ListView listView;
	private static AccountService accs;
	private static ItemService items;
	private long mExitTime;
	private TextView datetime;
	private TextView month;
	private TextView  pmonth;
	private TextView  nmonth;
	private TextView  tzhichu;
	private int aid;
	private  List<AccountList> cur;
	private AccountList lacc;
	private String Iyear;
	public static int iyear;
	public static int imonth;
	public String Imonth;
	public static int gv=-1;
	private  static int total=0;
	private static  int mday=0;
	public static  int curday=-1;
	private Handler handler = new Handler();
	private boolean isMoved;
	private int touchX;
	private int touchY;
	private static int flag=1;
	public  static SQLiteDatabase  db =null;


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.one);
		oneActivity.flag=0;

		DBOpenHelper dbOpenHelper = new DBOpenHelper(this);
		db= dbOpenHelper.getWritableDatabase();


		accs = new AccountService(this);
		items = new ItemService(this);

		Time time = new Time();
		time.setToNow();
		Iyear = String.valueOf(time.year);
		Imonth = String.format("%02d", time.month+1);

		iyear = time.year;
		imonth =  time.month+1;
		mday=time.monthDay;
		curday = time.monthDay;


		tzhichu = (TextView) this.findViewById(R.id.zhichu);
		pmonth = (TextView) this.findViewById(R.id.pmonth);
		nmonth = (TextView) this.findViewById(R.id.nmonth);

		dateview = (GridView) findViewById(R.id.dateview);
		datetime = (TextView)this.findViewById(R.id.datetime);

		listView = (ListView) this.findViewById(R.id.listView);


		datetime.setOnLongClickListener(new OnLongClickListener() {

			@Override
			public boolean onLongClick(View v) {
				addemail.Builder builder = new addemail.Builder(oneActivity.this);
				builder.create(items).show();
				return false;
			}
		});
		    
		    /*滑动事件处理*/
//		    dateview.setOnTouchListener(new OnTouchListener() {
//
//				@Override
//				public boolean onTouch(View v, MotionEvent event) {
//					 switch(event.getAction()) {
//
//                     case MotionEvent.ACTION_DOWN:
//
//                             isMoved = false;
//
//                             touchX = (int)event.getX();
//                             touchY = (int)event.getY();
//
//                             break;
//
//                     case MotionEvent.ACTION_UP :
//
//                             if(isMoved==true)
//                             {
//                            	 int offsetx = (int)event.getX()-touchX;
//                            	 int offsety = (int)event.getY()-touchY;
//
////                            	 pmonth.setText("x:"+String.valueOf(offsetx));
////                            	 nmonth.setText("y:"+String.valueOf(offsety));
//
//                            	 if(offsetx >200)
//                            	 {
//
//                 					imonth--;
//                 					if(imonth==0)
//                 					{
//                 						iyear--;
//                 						imonth=12;
//                 					}
//
//                 					curday=-1;
//                 					tzhichu.setText(String.format("%.1f",accs.getZSum("1",iyear,imonth)));
//                 					datetime.setText(String.valueOf(iyear)+"年"+String.format("%02d", imonth)+"月");
//                 					 getData(iyear,imonth);
//                 					 String [] from ={"text","sum"};
//                 				     int [] to = {R.id.mon,R.id.msum};
////                 					 sim_adapter = new SimpleAdapter(oneActivity.this, data_list, R.layout.dateitem, from, to);
//
//                 				     gridadapter sim_adapter = new gridadapter(oneActivity.this, data_list,imonth,99);
//                 				     dateview.setAdapter(sim_adapter);
//                 				     oneActivity.gv = -1;
//                 				     Time time = new Time();
//                 				        time.setToNow();
//
//                 				     if(iyear==time.year && imonth==time.month)
//                 				     {
//                 				    	 cur = accs.getListData(iyear,imonth,time.monthDay);
//                 				     }else
//                 				     {
//                 				    	 cur = accs.getListData(iyear,imonth,99);
//                 				     }
//
//
//                 			         //显示查询数据
//                 			         ListViewAdapter adapter = new ListViewAdapter(oneActivity.this,cur,items);
//                 			         listView.setAdapter(adapter);
//                 			         listView.setDivider(new ColorDrawable(Color.GRAY));
//                 			         listView.setDividerHeight(1);
//                 			         setListViewHeightBasedOnChildren(listView);
//
//
//                            	 }else if(offsetx<-200)
//                            	 {
//                            		 imonth++;
//                 					if(imonth==13)
//                 					{
//                 						iyear++;
//                 						imonth=1;
//                 					}
//                 					curday=-1;
//                 					tzhichu.setText(String.format("%.1f",accs.getZSum("1",iyear,imonth)));
//                 					datetime.setText(String.valueOf(iyear)+"年"+String.format("%02d", imonth)+"月");
//                 					getData(iyear,imonth);
//
//                 				     gridadapter sim_adapter = new gridadapter(oneActivity.this, data_list,imonth,99);
//                 					 dateview.setAdapter(sim_adapter);
//
//                 					 gv = -1;
//                 					 Time time = new Time();
//                 				        time.setToNow();
//
//                 				     if(iyear==time.year && imonth==time.month)
//                 				     {
//                 				    	 cur = accs.getListData(iyear,imonth,time.monthDay);
//                 				     }else
//                 				     {
//                 				    	 cur = accs.getListData(iyear,imonth,99);
//                 				     }
//
//                 			         //显示查询数据
//                 			         ListViewAdapter adapter = new ListViewAdapter(oneActivity.this,cur,items);
//                 			         listView.setAdapter(adapter);
//                 			         listView.setDivider(new ColorDrawable(Color.GRAY));
//                 			         listView.setDividerHeight(1);
//                 			         setListViewHeightBasedOnChildren(listView);
//                            	 }
////                            	 return true;
//                             }
////                             else{
////                            	 return false;
////                             }
//                             break;
//
//                     case MotionEvent.ACTION_MOVE:
//
//                             isMoved = true;
//                             break;
//                     }
//					return false;
//				}
//			});





		//接收邮件
		recvMailTread recv = new recvMailTread(items,this,handler,tzhichu,listView,dateview);
		recv.start();

		tzhichu.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				search.Builder builder = new search.Builder(oneActivity.this);

				builder.create(oneActivity.this,accs,iyear,imonth,items).show();
			}
		});

		tzhichu.setOnLongClickListener(new OnLongClickListener() {

			@Override
			public boolean onLongClick(View v) {
				CountDialog.Builder builder = new CountDialog.Builder(oneActivity.this);
				builder.create(oneActivity.this,items).show();

				return false;
			}
		});


		//记一笔按钮点击事件
		TextView button2 = (TextView)this.findViewById(R.id.btn_frame);

		button2.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {

				if(curday==-1)
				{
					Toast.makeText(oneActivity.this, "请选择日期", Toast.LENGTH_SHORT).show();
				}else
				{
//	        					InsertAmt.Builder builder = new InsertAmt.Builder(oneActivity.this);
//
//
//		        				builder.create(gv,tzhichu,dateview,listView,oneActivity.this,accs,iyear,imonth,curday,items).show();

					Intent intent = new Intent();
					intent.setClass(oneActivity.this, twoActivity.class);
					intent.putExtra("year", iyear);
					intent.putExtra("month", imonth);
					intent.putExtra("day", curday);
					startActivityForResult(intent, 0);
//	        					oneActivity.this.startActivity(intent);
				}


			}

		});

		//月支出总金额
		tzhichu.setText(String.format("%.1f",accs.getZSum("1",time.year,time.month+1)));


		//日期
		datetime.setText(String.valueOf(time.year)+"年"+String.format("%02d", time.month+1)+"月");

		cur = accs.getListData(time.year,time.month+1,curday);

		//显示查询数据
		ListViewAdapter adapter = new ListViewAdapter(this,cur,items);
		listView.setAdapter(adapter);
		listView.setDivider(new ColorDrawable(Color.GRAY));
		listView.setDividerHeight(1);


		listView.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view,
										   int position, long id) {
				lacc=(AccountList) parent.getItemAtPosition(position);

				aid = lacc.getId();


				AlertDialog.Builder builder = new AlertDialog.Builder(oneActivity.this);
				builder.setMessage("确定要删除吗？");

				builder.setPositiveButton("删除", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						accs.updateBalance(lacc, 0);
						lacc.setId(0);

						ArrayList<AccountList> arr = new ArrayList<AccountList>();
						arr.add(lacc);

//							    EmailService.sendMail(arr,items);

						sendEmailTread tread = new sendEmailTread(arr, items,accs);
						tread.start();

						List<AccountList> cur1 = accs.getListData(iyear,imonth,curday);
						ListViewAdapter adapter = new ListViewAdapter(oneActivity.this,cur1,items);
						listView.setAdapter(adapter);
						int sgv=gv;
						getData(iyear,imonth);
						gridadapter sim_adapter = new gridadapter(oneActivity.this, data_list,imonth,curday);
						dateview.setAdapter(sim_adapter);
						gv=sgv;

						tzhichu.setText(String.format("%.1f",accs.getZSum("1",iyear,imonth)));

					}
				}) ;

				builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.dismiss();
					}
				}) ;
				builder.create().show();
				return false;
			}
		});


		data_list = new ArrayList<Map<String, Object>>();

		pmonth.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				imonth--;
				if(imonth==0)
				{
					iyear--;
					imonth=12;
				}

				curday=-1;
				tzhichu.setText(String.format("%.1f",accs.getZSum("1",iyear,imonth)));
				datetime.setText(String.valueOf(iyear)+"年"+String.format("%02d", imonth)+"月");
				getData(iyear,imonth);
				String [] from ={"text","sum"};
				int [] to = {R.id.mon,R.id.msum};
//					 sim_adapter = new SimpleAdapter(oneActivity.this, data_list, R.layout.dateitem, from, to);

				gridadapter sim_adapter = new gridadapter(oneActivity.this, data_list,imonth,99);
				dateview.setAdapter(sim_adapter);
				oneActivity.gv = -1;
				Time time = new Time();
				time.setToNow();

//				     if(iyear==time.year && imonth==(time.month+1))
//				     {
//				    	 cur = accs.getListData(iyear,imonth,time.monthDay);
//				     }else
//				     {
				cur = accs.getListData(iyear,imonth,99);
//				     }


				//显示查询数据
				ListViewAdapter adapter = new ListViewAdapter(oneActivity.this,cur,items);
				listView.setAdapter(adapter);
				listView.setDivider(new ColorDrawable(Color.GRAY));
				listView.setDividerHeight(1);

			}
		});

		nmonth.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				imonth++;
				if(imonth==13)
				{
					iyear++;
					imonth=1;
				}
				curday=-1;
				tzhichu.setText(String.format("%.1f",accs.getZSum("1",iyear,imonth)));
				datetime.setText(String.valueOf(iyear)+"年"+String.format("%02d", imonth)+"月");
				getData(iyear,imonth);

				gridadapter sim_adapter = new gridadapter(oneActivity.this, data_list,imonth,99);
				dateview.setAdapter(sim_adapter);

				gv = -1;
				Time time = new Time();
				time.setToNow();
//
//				     if(iyear==time.year && imonth==(time.month+1))
//				     {
//				    	 cur = accs.getListData(iyear,imonth,time.monthDay);
//				     }else
//				     {
				cur = accs.getListData(iyear,imonth,99);
//				     }

				//显示查询数据
				ListViewAdapter adapter = new ListViewAdapter(oneActivity.this,cur,items);
				listView.setAdapter(adapter);
				listView.setDivider(new ColorDrawable(Color.GRAY));
				listView.setDividerHeight(1);
			}
		});



		getData(time.year,time.month+1);
		gridadapter sim_adapter = new gridadapter(this, data_list,time.month+1,curday);
		dateview.setAdapter(sim_adapter);




		dateview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
									int position, long id) {

				HashMap<String, Object> item=(HashMap<String, Object>) parent.getItemAtPosition(position);
				String tag =  item.get("text").toString();
				System.out.println("gv="+gv);
				if(gv!=-1)
				{
					if(gv==position)
					{
						view.setBackgroundColor(Color.WHITE);
						gv=-1;

//							if(!tag.equals(" "))
//						    {

						cur = accs.getListData(iyear,imonth,99);
						curday=-1;
						//显示查询数据
						ListViewAdapter adapter = new ListViewAdapter(oneActivity.this,cur,items);
						listView.setAdapter(adapter);
						listView.setDivider(new ColorDrawable(Color.GRAY));
						listView.setDividerHeight(1);
//						    }
					}else
					{
						System.out.println("========"+gv);
						View v =  parent.getChildAt(gv);
						v.setBackgroundColor(Color.WHITE);
						view.setBackgroundColor(Color.GRAY);
						gv = position;

						if(!tag.equals(" "))
						{

							curday=Integer.parseInt(tag);
							cur = accs.getListData(iyear,imonth,Integer.parseInt(tag));

							//显示查询数据
							ListViewAdapter adapter = new ListViewAdapter(oneActivity.this,cur,items);
							listView.setAdapter(adapter);
							listView.setDivider(new ColorDrawable(Color.GRAY));
							listView.setDividerHeight(1);
						}else
						{
							curday=-1;
							cur = accs.getListData(iyear,imonth,99);

							//显示查询数据
							ListViewAdapter adapter = new ListViewAdapter(oneActivity.this,cur,items);
							listView.setAdapter(adapter);
							listView.setDivider(new ColorDrawable(Color.GRAY));
							listView.setDividerHeight(1);
						}

					}
				}else
				{
					view.setBackgroundColor(Color.GRAY);
					gv = position;


					if(!tag.equals(" "))
					{
						curday=Integer.parseInt(tag);
						cur = accs.getListData(iyear,imonth,Integer.parseInt(tag));

						//显示查询数据
						ListViewAdapter adapter = new ListViewAdapter(oneActivity.this,cur,items);
						listView.setAdapter(adapter);
						listView.setDivider(new ColorDrawable(Color.GRAY));
						listView.setDividerHeight(1);
					}else
					{
						curday=-1;
						cur = accs.getListData(iyear,imonth,99);

						//显示查询数据
						ListViewAdapter adapter = new ListViewAdapter(oneActivity.this,cur,items);
						listView.setAdapter(adapter);
						listView.setDivider(new ColorDrawable(Color.GRAY));
						listView.setDividerHeight(1);
					}
				}

			}
		});


	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		List<Map<String, Object>> list = oneActivity.getData(iyear,imonth);
		gridadapter sim_adapter = new gridadapter(this, list,imonth,curday);
		dateview.setAdapter(sim_adapter);


		List<AccountList> cur1 = accs.getListData(iyear,imonth,curday);
		ListViewAdapter adapter = new ListViewAdapter(this,cur1,items);
		listView.setAdapter(adapter);

		tzhichu.setText(String.format("%.1f",accs.getZSum("1",iyear,imonth)));

		super.onActivityResult(requestCode, resultCode, data);
	}


	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {

			exit();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	public void exit() {
		if ((System.currentTimeMillis() - mExitTime) > 2000) {
			Toast.makeText(oneActivity.this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
			mExitTime = System.currentTimeMillis();




		} else {

			oneActivity.flag=1;
			finish();
	        /*finish是Activity的类，仅仅针对Activity，
	         * 当调用finish()时，只是将活动推向后台，
	         * 并没有立即释放内存，活动的资源并没有被清理；
	         * 当调用System.exit(0)时，杀死了整个进程，
	         * 这时候活动所占的资源也会被释放。*/


			Timer timer = new Timer();

			timer.schedule(new TimerTask() {

				public void run() {
					if(oneActivity.flag==1)
					{
//	            		log("执行");
						System.exit(0);

					}else
					{
//	            		log("没执行");
					}


				}

			}, 10000);
		}
	}


//	public static void setListViewHeightBasedOnChildren(ListView listView) {
//        ListAdapter listAdapter = listView.getAdapter();
//        if (listAdapter == null) {
//            return;
//        }
//
//        int totalHeight = 0;
//        for (int i = 0; i < listAdapter.getCount(); i++) {
//            View listItem = listAdapter.getView(i, null, listView);
//
//            listItem.measure(0, 0);
//            totalHeight += listItem.getMeasuredHeight();
//
//        }
//
//        ViewGroup.LayoutParams params = listView.getLayoutParams();
//        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
//
//        listView.setLayoutParams(params);
//    }

	public static List<Map<String, Object>> getData(int year,int month)
	{
		int sum=0;
		data_list.clear();
		SimpleDateFormat sm = new SimpleDateFormat("yyyyMMdd");


		try {
			Date  date = sm.parse(String.format("%04d%02d", year,month)+"01");
			int day = date.getDay();

			for(int i =0;i<day;i++)
			{
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("text", " ");
				map.put("sum", " ");
				data_list.add(map);
			}
			sum = sum+day;

			if(month==1 || month==3 || month==5 || month==7 || month==8 || month==10 || month==12)
			{

				for(int i=1;i<=31;i++){
					if(oneActivity.mday==i)
					{
						gv=sum+i-1;

					}
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("text", String.valueOf(i));

					double amt = accs.getZSumDay(year,month,i);
					if(amt==0)
					{
						map.put("sum", " ");
					}else
					{

						map.put("sum", String.format("%.1f",amt));
					}

					data_list.add(map);
				}
				sum= sum+31;

			}else if(month==4 || month==6 || month==9 || month==11 )
			{
				for(int i=1;i<=30;i++){
					if(oneActivity.mday==i)
					{
						gv=sum+i-1;
					}
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("text", String.valueOf(i));
					double amt = accs.getZSumDay(year,month,i);
					if(amt==0)
					{
						map.put("sum", " ");
					}else
					{
						map.put("sum", String.format("%.1f",amt));
					}
					data_list.add(map);
				}
				sum=sum+30;
			}else if(month == 2)
			{
				if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
					for(int i=1;i<=29;i++){
						if(oneActivity.mday==i)
						{
							gv=sum+i-1;
						}
						Map<String, Object> map = new HashMap<String, Object>();
						map.put("text", String.valueOf(i));
						double amt = accs.getZSumDay(year,month,i);
						if(amt==0)
						{
							map.put("sum", " ");
						}else
						{
							map.put("sum", String.format("%.1f",amt));
						}
						data_list.add(map);
					}
					sum=sum+29;
				} else {
					for(int i=1;i<=28;i++){
						if(oneActivity.mday==i)
						{
							gv=sum+i;
						}
						Map<String, Object> map = new HashMap<String, Object>();
						map.put("text", String.valueOf(i));
						double amt = accs.getZSumDay(year,month,i);
						if(amt==0)
						{
							map.put("sum", " ");
						}else
						{
							map.put("sum", String.format("%.1f",amt));
						}
						data_list.add(map);
					}
					sum=sum+28;
				}
			}
			int len=0;
			if(sum>35)
			{
				len=42-sum;
				total=42;
			}else
			{
				len=35-sum;
				total=35;
			}

			for(int i=0;i<len;i++)
			{
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("text", " ");
				map.put("sum", " ");
				data_list.add(map);
			}

		} catch (ParseException e) {
			e.printStackTrace();
		}

		return data_list;
	}

	public static  String getSDPath(){
		File sdDir = null;
		boolean sdCardExist = Environment.getExternalStorageState()
				.equals(android.os.Environment.MEDIA_MOUNTED);  //判断sd卡是否存在
		if  (sdCardExist)
		{
			sdDir = Environment.getExternalStorageDirectory();//获取跟目录
		}
		return sdDir.toString();

	}

	public static void  log(String val)
	{
		File f = new File(getSDPath()+"/note.log");


		try {
			FileWriter out = new FileWriter(f,true);
			out.write(val+"\n");
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();

		oneActivity.db.close();

	}



}
